package com.gec.anan.rules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gec.anan.model.entity.rule.FeeRule;
import com.gec.anan.model.form.rules.FeeRuleRequest;
import com.gec.anan.model.form.rules.FeeRuleRequestForm;
import com.gec.anan.model.vo.rules.FeeRuleResponse;
import com.gec.anan.model.vo.rules.FeeRuleResponseVo;
import com.gec.anan.rules.mapper.FeeRuleMapper;
import com.gec.anan.rules.service.FeeRuleService;
import com.gec.anan.rules.utils.DroolsHelper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class FeeRuleServiceImpl implements FeeRuleService {

    @Autowired
    private FeeRuleMapper feeRuleMapper;
    @Override

    public FeeRuleResponseVo calculateOrderFee(FeeRuleRequestForm ruleRequestForm) {
        //创建规则的参数
        FeeRuleRequest feeRuleRequest = new FeeRuleRequest();
        //设置客户端传来的参数
        feeRuleRequest.setDistance(ruleRequestForm.getDistance());
        feeRuleRequest.setWaitMinute(ruleRequestForm.getWaitMinute());
        feeRuleRequest.setStartTime(new DateTime(ruleRequestForm.getStartTime()).toString("HH:mm:ss"));
        //获取最新规则文件
        FeeRule feeRule = feeRuleMapper.selectOne(new LambdaQueryWrapper<FeeRule>()
                .orderByDesc(FeeRule::getId).last("limit 1"));

        //开启规则
        KieSession kieSession = DroolsHelper.loadForRule(feeRule.getRule());
        //设置封装对象
        FeeRuleResponse feeRuleResponse = new FeeRuleResponse();
        kieSession.setGlobal("feeRuleResponse",feeRuleResponse);
        //放入工作内存
        kieSession.insert(feeRuleRequest);
        //激活规则
        kieSession.fireAllRules();
        //关闭
        kieSession.dispose();
        //封装返回对象
        FeeRuleResponseVo feeRuleResponseVo = new FeeRuleResponseVo();
        BeanUtils.copyProperties(feeRuleResponse, feeRuleResponseVo);
        return feeRuleResponseVo;
    }
}
